<template>
    <div>
        <label v-if="label" >{{ label }}</label>
        <div>
            <!-- input 位置 -->
            <slot></slot>
            <p class="error" v-if="validateStatus === 'error'" >
                {{ errorMessage }}
            </p>
        </div>
    </div>
</template>

<script>
import Schema from 'async-validator';

    export default {
        inject: ['form'],
        props: ['label', 'prop'],
        data() {
            return {
                errorMessage: '',
                validateStatus: ''
            }
        },
        created() {
            this.$on('validate', this.validate)
        },
        mounted() {
            if (this.prop) {
                this.$parent.$emit('formItemAdd', this)
            }
        },
        methods: {
            validate() {
                return new Promise((resolve) => {
                    let rule = {
                        [this.prop]: this.form.rules[this.prop]
                    }
                    const validator = new Schema(rule)
                    const data = {[this.prop]: this.form.model[this.prop]}
                    validator.validate(data, errors => {
                        if (errors) {
                            this.errorMessage = errors[0].message
                            this.validateStatus = 'error'
                            resolve(false)
                        } else {
                            this.errorMessage = ''
                            this.validateStatus = ''
                            resolve(true)
                        }
                    })
                })
            }
        }
    }
</script>

<style lang="css" scoped>
.error{
    color: red
}
</style>